/**
 * @description 
 * @author cq
 * @Date 2021-04-27 10:20:52
 * @LastEditTime 2021-04-28 10:18:40
 * @LastEditors cq
 */

export default ()=>{
  return new Promise((resolve,reject)=>{
    var promise = navigator.mediaDevices.getUserMedia({
      audio: true,
      // video: { width: 1280, height: 720 }
    });
    
  })
}




if (navigator.mediaDevices.getUserMedia) {
  const constraints = { audio: true };
  navigator.mediaDevices.getUserMedia(constraints).then(
    stream => {
      console.log("授权成功！");
      // var mediaRecorder = new MediaRecorder(stream);

      const recordBtn = document.querySelector(".record-btn");
      const mediaRecorder = new MediaRecorder(stream);
      recordBtn.onclick = () => {
        mediaRecorder.start();
        console.log("录音中...");
      };


      recordBtn.onclick = () => {
        if (mediaRecorder.state === "recording") {
          mediaRecorder.stop();
          recordBtn.textContent = "record";
          console.log("录音结束");
        } else {
          mediaRecorder.start();
          console.log("录音中...");
          recordBtn.textContent = "stop";
        }
        console.log("录音器状态：", mediaRecorder.state);
      };


      var chunks = [];
      mediaRecorder.ondataavailable = function (e) {
        chunks.push(e.data);
      };

      mediaRecorder.onstop = e => {
        console.log("暂停播放")
        var blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
        console.log(blob,"blob")
        var audio = document.querySelector(".audio-player");
        chunks = [];
        // 
        // arrybuffer_voice_send_recv_play(blob)
        // console.log(111)
        var audioURL = window.URL.createObjectURL(blob);
        console.log(audioURL,"audioURL")
        audio.src = audioURL;
      };

      function arry2str(Arry2str) {// string with ','
        return Arry2str.join(',');//arry2str
      }


      function arrybuffer_voice_send_recv_play(blob_exch) {
        console.log("没进来吗")
        console.log(blob_exch);
        //将Blob 对象转换成 ArrayBuffer
        var reader = new FileReader();
        //reader.readAsArrayBuffer(blob_exch,'utf-16');
        reader.readAsArrayBuffer(blob_exch, 'utf-8');
        reader.onload = function (e) {
          var abf = reader.result;
          var typedArray = new Uint8Array(abf);
          console.log(typedArray);
          var str_vt = arry2str(typedArray);//arrybuffer to string 
          console.log(str_vt,111);
          // adhoc.addPcmVoiceListener_spe_api(voicedatacallback, str_vt);
        }
      }

    },
    () => {
      console.error("授权失败！");
    }
  );
} else {
  console.error("浏览器不支持 getUserMedia");
}
